/**
 * Created by ckto1212@gmail.com
 */
package com.welbell.android.extension.communication;

import java.io.File;
import java.io.IOException;

import com.welbell.android.communication.BaseActivity;
import com.welbell.android.communication.R;
import com.welbell.android.communication.model.CommunicationKeySet;
import com.welbell.android.communication.model.Device;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.Chronometer;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * @author wangzong
 */
public class CommunicationActivity extends BaseActivity {

	private TextView roomNumOrAliasesTextView;
	private TextView roomNumTextView;
	private Chronometer communicationChronometer;
	private RelativeLayout screenShotButton;
	private RelativeLayout soundButton;
	private CheckBox micSwitch;

	private RelativeLayout InComingCallRelativeLayout;
	private ImageButton hangupImageButton;
	private ImageButton answerImageButton;
	private ImageButton openLockImageButton;

	private RelativeLayout HostAnsweredRelativeLayout;
	private ImageButton hostAnsweredHangupImageButton;
	private ImageButton hostAndweredOpenLockImageButton;

	private RelativeLayout extentionAnsweredRelativeLayout;
	private ImageButton extentionAnsweredHangupImageButton;

	private SurfaceView remoteVideoSurfaceView;
	private RelativeLayout preRemoteVideoSurfaceView;

	private TextView talkStateTextView;
	private TextView talkSourceTextView;

	private FrameLayout localVideoSurfaceViewFrameLayout;
	private ImageView preLocalVideoSurfaceViewImageView;
	private SurfaceView localVideoSurfaceView;

	private CheckBox showLocalVideo;

	private Device tempDevice;

	private boolean isDoorHasBeenOpened = false;

	private float talkVolumn = -1;
	private float toneVolumn = -1;
	private String toneLocation;

	private final int ANSWERSUCCESSED = 0x01;
	private final int OPENLOCKSUCCESS = 0x03;
	private final int HANGUPSUCCESSED = 0x04;

	private final int DISMISSPREREMOTESURFACE = 0x05;
	private final int DISMISSPRELOCALSURFACE = 0x06;

	private final int FINISHACTIVITY = 0x07;

	private final int SHOWLOCALSURFACEVIEW = 0x08;

	private final int RESTARTCHRONMETER = 0x09;

	@SuppressLint("HandlerLeak")
	private Handler uiHanlder = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ANSWERSUCCESSED:
				talkStateTextView.setText(getResources().getString(R.string.communicationStateAnswered));
				switch (tempDevice.getDeviceType()) {
				case Host:
					showLocalVideo.setChecked(false);
					showLocalVideo.setClickable(false);
					preRemoteVideoSurfaceView.setVisibility(View.INVISIBLE);
					InComingCallRelativeLayout.setVisibility(View.INVISIBLE);
					HostAnsweredRelativeLayout.setVisibility(View.VISIBLE);
					break;
				case Extension:
					InComingCallRelativeLayout.setVisibility(View.INVISIBLE);
					extentionAnsweredRelativeLayout.setVisibility(View.VISIBLE);
					break;
				default:
					break;
				}
				break;
			case OPENLOCKSUCCESS:
				break;
			case HANGUPSUCCESSED:
				break;
			case DISMISSPREREMOTESURFACE:
				preRemoteVideoSurfaceView.setVisibility(View.INVISIBLE);
				break;
			case DISMISSPRELOCALSURFACE:
				preLocalVideoSurfaceViewImageView.setVisibility(View.INVISIBLE);
				break;
			case FINISHACTIVITY:
				CommunicationActivity.this.finish();
				break;
			case SHOWLOCALSURFACEVIEW:
				// if (localVideoSurfaceViewFrameLayout.getVisibility() ==
				// View.INVISIBLE) {
				// localVideoSurfaceViewFrameLayout.setVisibility(View.VISIBLE);
				// }
				break;
			case RESTARTCHRONMETER:
				communicationChronometer.stop();
				communicationChronometer.setBase(SystemClock.elapsedRealtime());
				communicationChronometer.start();
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.communication);

		roomNumOrAliasesTextView = (TextView) findViewById(R.id.roomNumOrAliasesTextView);
		roomNumTextView = (TextView) findViewById(R.id.roomNumTextView);
		talkStateTextView = (TextView) findViewById(R.id.talkStateTextView);
		talkSourceTextView = (TextView) findViewById(R.id.talkSourceTextView);

		communicationChronometer = (Chronometer) findViewById(R.id.communicationChronometer);

		screenShotButton = (RelativeLayout) findViewById(R.id.screenShotButton);
		soundButton = (RelativeLayout) findViewById(R.id.soundButton);
		InComingCallRelativeLayout = (RelativeLayout) findViewById(R.id.InComingCallRelativeLayout);
		HostAnsweredRelativeLayout = (RelativeLayout) findViewById(R.id.HostAnsweredRelativeLayout);
		extentionAnsweredRelativeLayout = (RelativeLayout) findViewById(R.id.ExtentionAnsweredRelativeLayout);

		micSwitch = (CheckBox) findViewById(R.id.micSwitch);
		showLocalVideo = (CheckBox) findViewById(R.id.showLocalVideo);

		hangupImageButton = (ImageButton) findViewById(R.id.hangupImageButton);
		answerImageButton = (ImageButton) findViewById(R.id.answerImageButton);
		openLockImageButton = (ImageButton) findViewById(R.id.openLockImageButton);
		hostAnsweredHangupImageButton = (ImageButton) findViewById(R.id.hostAnsweredHangupImageButton);
		hostAndweredOpenLockImageButton = (ImageButton) findViewById(R.id.hostAndweredOpenLockImageButton);
		extentionAnsweredHangupImageButton = (ImageButton) findViewById(R.id.extentionAnsweredHangupImageButton);

		remoteVideoSurfaceView = (SurfaceView) findViewById(R.id.remoteVideoSurfaceView);
		localVideoSurfaceView = (SurfaceView) findViewById(R.id.localVideoSurfaceView);

		preRemoteVideoSurfaceView = (RelativeLayout) findViewById(R.id.preRemoteVideoSurfaceView);
		preLocalVideoSurfaceViewImageView = (ImageView) findViewById(R.id.preLocalVideoSurfaceViewImageView);

		localVideoSurfaceViewFrameLayout = (FrameLayout) findViewById(R.id.localVideoSurfaceViewFrameLayout);

		micSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

			}
		});
		screenShotButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

			}
		});

		hangupImageButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				log("HANGUP");
				CommunicationActivity.super.hangup();
			}
		});
		answerImageButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				log("ANSWER");
				CommunicationActivity.super.answer();
			}
		});
		openLockImageButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				log("OPENLOCK");
				CommunicationActivity.super.openlock();
			}
		});

		hostAnsweredHangupImageButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				log("HANGUP");
				CommunicationActivity.super.hangup();
			}
		});

		hostAndweredOpenLockImageButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				log("OPENLOCK");
				CommunicationActivity.super.openlock();
			}
		});

		extentionAnsweredHangupImageButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				log("HANGUP");
				CommunicationActivity.super.hangup();
			}
		});

		/*
		 * =========================================================
		 * 
		 * 其他部分传递过来的参数的检测，或做成有返回值的Activity的模式
		 * 
		 * =========================================================
		 */
		Bundle bundle = getIntent().getBundleExtra(CommunicationKeySet.CommunicationContackKey);
		if (bundle != null) {
			log("Get Service Data");
			tempDevice = (Device) bundle.get(CommunicationKeySet.CommunicationContackKey);
			if (tempDevice != null) {
				log("DeviceInfo:" + tempDevice.getDeviceInfo());
			} else {
				log("Get ContactInfo Failed");
			}
			switch (bundle.getInt(CommunicationKeySet.CommunicationTalkKey)) {
			case CommunicationKeySet.CommunicationINCOMINGCALLCODE:
				talkStateTextView.setText(getResources().getString(R.string.communicationStateInComingCall));
				remoteVideoSurfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
					@Override
					public void surfaceDestroyed(SurfaceHolder holder) {

					}

					@Override
					public void surfaceCreated(SurfaceHolder holder) {
						log("Remote SurfaceView Created");
						CommunicationActivity.super.startRemoteVideoDisplay(remoteVideoSurfaceView);
					}

					@Override
					public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

					}
				});
				log("    ****    INCOMINGCALL");
				switch (tempDevice.getDeviceType()) {
				case Host:
					log("    ****    HOST INCOMINGCALL");
					if (InComingCallRelativeLayout != null) {
						InComingCallRelativeLayout.setVisibility(View.VISIBLE);
					}
					if (tempDevice.getDevNum() < 9) {
						roomNumOrAliasesTextView.setText("0" + tempDevice.getDevNum() + "号主机");
					} else {
						roomNumOrAliasesTextView.setText(tempDevice.getDevNum() + "号主机");
					}
					break;
				case Extension:
					log("    ****    Extension INCOMINGCALL");
					if (InComingCallRelativeLayout != null) {
						InComingCallRelativeLayout.setVisibility(View.VISIBLE);
					}
					if (openLockImageButton != null) {
						openLockImageButton.setBackgroundResource(R.drawable.dialpad_unlock_blocked);
					}
					StringBuffer buffer = new StringBuffer();
					if (tempDevice.getZone() < 10) {
						buffer.append("0");
					}
					buffer.append(tempDevice.getZone()).append("区");
					if (tempDevice.getBuild() < 10) {
						buffer.append("0");
					}
					buffer.append(tempDevice.getBuild()).append("栋");
					if (tempDevice.getUnit() < 10) {
						buffer.append("0");
					}
					buffer.append(tempDevice.getUnit()).append("单元");
					if (tempDevice.getFloor() < 10) {
						buffer.append("0");
					}
					buffer.append(tempDevice.getFloor());
					if (tempDevice.getRoom() < 10) {
						buffer.append("0");
					}
					buffer.append(tempDevice.getRoom()).append("室");
					roomNumOrAliasesTextView.setText(buffer.toString());
					break;
				default:
					break;
				}
				break;
			case CommunicationKeySet.CommunicationCALLOTHERSCODE:
				talkStateTextView.setText(getResources().getString(R.string.communicationStateAnswereing));
				log("    ****    CALL OTHERS");
				switch (tempDevice.getDeviceType()) {
				case Extension:
					log("    ****    CALL Extension    DeviceInfo:" + tempDevice.getDeviceInfo());
					extentionAnsweredRelativeLayout.setVisibility(View.VISIBLE);
					log("Calling Ring");
					showLocalVideo.setChecked(true);
					// localVideoSurfaceViewFrameLayout.setVisibility(View.VISIBLE);
					// localVideoSurfaceView.setVisibility(View.VISIBLE);
					localVideoSurfaceView.getHolder().addCallback(new Callback() {
						@Override
						public void surfaceDestroyed(SurfaceHolder holder) {
						}

						@Override
						public void surfaceCreated(SurfaceHolder holder) {
							log("Start local Video Displayer");
							CommunicationActivity.super.startLocalCameraVideoDisplayAndSend(localVideoSurfaceView);
						}

						@Override
						public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
						}
					});
					StringBuffer buffer = new StringBuffer();
					if (tempDevice.getZone() < 10) {
						buffer.append("0");
					}
					buffer.append(tempDevice.getZone()).append("区");
					if (tempDevice.getBuild() < 10) {
						buffer.append("0");
					}
					buffer.append(tempDevice.getBuild()).append("栋");
					if (tempDevice.getUnit() < 10) {
						buffer.append("0");
					}
					buffer.append(tempDevice.getUnit()).append("单元");
					if (tempDevice.getFloor() < 10) {
						buffer.append("0");
					}
					buffer.append(tempDevice.getFloor());
					if (tempDevice.getRoom() < 10) {
						buffer.append("0");
					}
					buffer.append(tempDevice.getRoom()).append("室");
					roomNumOrAliasesTextView.setText(buffer.toString());
					break;
				default:
					break;
				}
				break;
			case CommunicationKeySet.CommunicationMONITOR:
				break;
			default:
				break;
			}
			communicationChronometer.setBase(SystemClock.elapsedRealtime());
			communicationChronometer.start();
			switch (tempDevice.getDeviceType()) {
			case Host:
				talkSourceTextView.setText(getResources().getString(R.string.communicationThroughHost));
				break;
			case Extension:
				talkSourceTextView.setText(getResources().getString(R.string.communicationThroughExtension));
				break;
			default:
				break;
			}
		} else {
			log("No Service Data");
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (ringstoneMediaPlayer != null) {

		}
	}

	private void log(String _log) {
		Log.v("CommunicationActivity", "    ====    " + _log);
	}

	private MediaPlayer ringstoneMediaPlayer;

	private void startRing(String stoneFilePath) {
		File stonePath = new File(stoneFilePath);
		if (stonePath != null && stonePath.exists()) {
			if (ringstoneMediaPlayer == null) {
				ringstoneMediaPlayer = new MediaPlayer();
			}
			try {
				ringstoneMediaPlayer.setDataSource(toneLocation);
				ringstoneMediaPlayer.prepare();
				if (toneVolumn != -1) {
					ringstoneMediaPlayer.setVolume(toneVolumn, toneVolumn);
				}
				ringstoneMediaPlayer.start();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void stopRing() {
		if (ringstoneMediaPlayer != null) {
			log("Stop Ring");
			ringstoneMediaPlayer.stop();
			ringstoneMediaPlayer.reset();
			ringstoneMediaPlayer.release();
		}
		ringstoneMediaPlayer = null;
	}

}
